// 加密
const JWT = require('jsonwebtoken')
// 导入全局配置文件
const config = require('../../config/config')
// 导入数据库处理模块
const db = require('../../mysql/index')
// 导入加密密码的包
const bcryptjs = require('bcryptjs')

// 注册
Register = (req, res) => {
    const user = req.body
    const registerSql1 = 'SELECT * FROM admins where username=?'
    db.query(registerSql1, user.username, (err, result) => {
        if (err) return res.cc(err)
        if (result.length === 1) return res.cc('用户名已被占用，请重新选择用户名', status = 401)
        // 加密密码
        user.password = bcryptjs.hashSync(user.password, 10)
        const token = JWT.sign({ userinfo: user.username }, config.secretKey, { expiresIn: config.expiresTime })
        const registerSql2 = 'INSERT INTO admins(username,password) VALUES(?,?)'
        db.query(registerSql2, [user.username, user.password], (err, result) => {
            if (err) return res.cc(err)
            if (result.affectedRows === 1) {
                res.send({
                    status: 0,
                    message: '注册成功',
                    token: 'Bearer ' + token,
                })
            }
        })
    })
}
// 登录
Login = (req, res) => {
    const user = req.body
    const loginSql = 'SELECT password from admins where username=?'
    db.query(loginSql, user.username, (err, result) => {
        if (result.length !== 1) return res.cc('用户不存在！！')
        const CompareResult = bcryptjs.compareSync(user.password, result[0].password)
        if (CompareResult) {
            const token = JWT.sign({ userinfo: user.username }, config.secretKey, { expiresIn: config.expiresTime })
            res.send({
                status: 0,
                message: '登录成功',
                token: 'Bearer ' + token
            })
        } else {
            res.cc("密码错误", status = 3)
        }
    })

}

module.exports = {
    Register,
    Login
}